import {_decorator, Component, systemEvent, SystemEventType, UITransform, Vec3, TypeScript, Script} from 'cc';
import { Data } from "./Data";
import {Game} from "./Game";

const { ccclass, property } = _decorator;

@ccclass('Player')
export class Player extends Component {
    /**
     * 玩家当前速度
     */
    private speed!: number;
    /**
     * 对外初始化接口
     */
    public init() {
        this.setProperties();
        this.initPlayerProperties();
    }
    /**
     * 初始化节点属性
     */
    private setProperties(){
        this.node.setPosition(new Vec3(Data.Player.xPos, 0));
        this.node.getComponent(UITransform)!.width = Data.Player.width;
        this.node.getComponent(UITransform)!.height = Data.Player.height;
    }
    /**
     * 初始化玩家属性
     */
    private initPlayerProperties(){
        this.speed = 0;
    }
    /**
     * 注册触摸事件监听
     */
    private onTouchListener(){
        systemEvent.on(SystemEventType.TOUCH_START, this.onTouch, this);
    }
    /**
     * 注销触摸事件监听
     */
    private offTouchListener(){
        systemEvent.off(SystemEventType.TOUCH_START, this.onTouch, this);
    }
    /**
     * 当玩家点击屏幕时 给player一个Y轴正方向的初速度
     */
    private onTouch() {
        this.speed = Data.Player.flyInitSpeed;
    }
    /**
     * player移动方法
     */
    private move(dt: number) {
        if ((Math.abs(this.speed) < Data.Player.yMaxSpeed)
            || (this.speed == Data.Player.yMaxSpeed)){
            this.speed -= Data.Player.accel;
        }
        this.node.setPosition((new Vec3(Data.Player.xPos, this.node.position.y + this.speed * dt + 0.5 * Data.Player.accel * dt * dt)))
    }
    /**
     * 子类实现
     */
    protected onLoad() {
        this.setProperties();
        this.onTouchListener();
    }

    protected start() {
        this.initPlayerProperties();
    }

    protected update(dt: number) {
        if (!Game.isPaused){
            this.move(dt);
        }

    }

    protected onDestroy() {
        this.offTouchListener();
    }
}